package mark.tom.fiter.http.ssl;

import android.annotation.SuppressLint;

import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class NoneSSLSocketFactory extends AbstractSSLSocketFactory {

    private final SSLContext sslContext = SSLContext.getInstance(TLS);
    private final X509TrustManager trustManager;

    private NoneSSLSocketFactory() throws NoSuchAlgorithmException,
            KeyManagementException {

        TrustManager[] tm = new TrustManager[]{new X509TrustManager() {
                    @SuppressLint("TrustAllX509TrustManager")
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @SuppressLint("TrustAllX509TrustManager")
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }};

        sslContext.init(null, tm, new SecureRandom());
        trustManager = (X509TrustManager) tm[0];
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    public static NoneSSLSocketFactory getHttpSSLSocketFactory() {
        NoneSSLSocketFactory socketFactory = null;
        try {
            socketFactory = new NoneSSLSocketFactory();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return socketFactory;
    }

    @Override
    public HostnameVerifier getHostnameVerifier() {
        return new HostnameVerifier() {
            @SuppressLint("BadHostnameVerifier")
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
    }

    @Override
    public X509TrustManager getTrustManager() {
        return trustManager;
    }
}
